<template>
  <view class="add-product-container">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <view class="search-input-wrapper">
        <uni-icons type="search" size="20" color="#999"></uni-icons>
        <input 
          class="search-input" 
          type="text" 
          placeholder="请输入商品名称或编码" 
          v-model="searchKeyword"
          @input="handleSearch"
        />
        <view class="clear-btn" v-if="searchKeyword" @click="clearSearch">
          <uni-icons type="clear" size="16" color="#999"></uni-icons>
        </view>
      </view>
    </view>
    
    <!-- 商品列表 -->
    <scroll-view class="product-scroll" scroll-y="true" :style="{ height: scrollHeight }">
      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading">
        <text class="loading-text">正在加载商品数据...</text>
      </view>
      
      <view class="product-list" v-else>
        <!-- 商品卡片 -->
        <view 
          class="product-card" 
          v-for="(product, index) in filteredProductList" 
          :key="product.rowid"
          @click="toggleProductSelection(product)"
        >
          <!-- 选中框 -->
          <view class="checkbox-wrapper">
            <view 
              class="checkbox" 
              :class="{ 'checkbox-checked': isProductSelected(product.rowid) }"
            >
              <uni-icons 
                v-if="isProductSelected(product.rowid)" 
                type="checkmarkempty" 
                size="16" 
                color="#fff"
              ></uni-icons>
            </view>
          </view>
          
          <!-- 商品图片 -->
          <view class="product-image">
            <image 
              :src="getFirstImage(product['6864930a4e2949f411990010'])" 
              mode="aspectFill"
              class="image"
            ></image>
          </view>
          
          <!-- 描述区域 -->
          <view class="product-info">
            <text class="product-name">{{ product['68634c1c87058ae1c65da306'] }}</text>
            <text class="product-code">商品条码：{{ product['68634c1c87058ae1c65da312'] }}</text>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-if="filteredProductList.length === 0">
          <text class="empty-text">暂无商品数据</text>
        </view>
      </view>
    </scroll-view>
    
    <!-- 底部确定按钮 -->
    <view class="bottom-actions">
      <button 
        class="confirm-btn" 
        :class="{ 'confirm-btn-disabled': selectedProducts.length === 0 }"
        :disabled="selectedProducts.length === 0"
        @click="handleConfirm"
      >
        确定 ({{ selectedProducts.length }})
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import http from '../../../utils/request'
import { callWorkflowListAPI, callWorkflowAPI } from '../../../utils/workflow'
import { useUserStore } from '../../../store/user'
import { onLoad, onReady, onUnload, onShow, onBackPress } from '@dcloudio/uni-app'
import { useTaskStore } from '../../../store/task'


const taskStore = useTaskStore()

// 搜索关键词
const searchKeyword = ref('')

// 选中的商品列表
const selectedProducts = ref([])

// 商品列表数据
const productList = ref([])

// 加载状态
const loading = ref(false)

// 接收到的供应商名称
const supplierName = ref('')
const supplierRowid = ref('')

// 滚动区域高度 (搜索栏高度 + 底部按钮高度 + 安全间距)
const scrollHeight = ref('calc(100vh - 120rpx - 148rpx)')

// 过滤后的商品列表
const filteredProductList = computed(() => {
  let filteredList = productList.value
  
  // 首先按供应商过滤
  if (supplierRowid.value) {
    filteredList = filteredList.filter(product => {
      try {
        const supplierField = product['6865ee3d57603df8e65ce609']
        if (!supplierField) {
          return false
        }
        
        const parsedSupplier = JSON.parse(supplierField)
        if (!Array.isArray(parsedSupplier) || parsedSupplier.length === 0) {
          return false
        }
        
        const firstSupplier = parsedSupplier[0]
        if (!firstSupplier || !firstSupplier['sourcevalue']) {
          return false
        }
        
        const productSupplierRowid = JSON.parse(firstSupplier['sourcevalue']).rowid
        return productSupplierRowid === supplierRowid.value
      } catch (error) {
        // 静默处理解析错误，不显示日志
        return false
      }
    })
  }
  
  console.log('过滤供应商后的商品列表:', filteredList)
  
  // 然后按搜索关键词过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filteredList = filteredList.filter(product => {
      const name = product['68634c1c87058ae1c65da306'] || ''
      const code = product['68634c1c87058ae1c65da312'] || ''
      
      return name.toLowerCase().includes(keyword) || code.toLowerCase().includes(keyword)
    })
  }
  
  console.log('过滤搜索关键词后的商品列表:', filteredList)
  
  return filteredList
})


// 处理搜索
const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
}

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = ''
}

// 切换商品选中状态
const toggleProductSelection = (product) => {
  const index = selectedProducts.value.findIndex(item => item.rowid === product.rowid)
  
  if (index > -1) {
    // 已选中，取消选中
    selectedProducts.value.splice(index, 1)
  } else {
    // 未选中，添加到选中列表
    selectedProducts.value.push(product)
  }
}

// 判断商品是否已选中
const isProductSelected = (productId) => {
  return selectedProducts.value.some(item => item.rowid === productId)
}

// 处理确定按钮点击
const handleConfirm = () => {
  if (selectedProducts.value.length === 0) {
    uni.showToast({
      title: '请选择商品',
      icon: 'none'
    })
    return
  }
 taskStore.setPendingTaskUpdate(selectedProducts.value)
 uni.navigateBack()
}

const getFirstImage = (imageData) => {
  if (!imageData) return ''
  
  try {
    // 如果已经是字符串数组，直接返回第一个
    if (Array.isArray(imageData)) {
      return imageData[0] || ''
    }
    
    // 如果是JSON字符串，解析后取第一个图片的thumbnail_full_path
    const parsedData = JSON.parse(imageData)
    if (Array.isArray(parsedData) && parsedData.length > 0) {
      return parsedData[0].thumbnail_full_path || parsedData[0].file_path || ''
    }
  } catch (error) {
    console.error('解析图片数据失败:', error)
  }
  
  return ''
}

const getProductData = async () => {
  try {
    loading.value = true
    const result = await callWorkflowListAPI('68634c1c87058ae1c65da305', [], 100, 0) 
    if(result && result.data) {
      console.log('商品数据:', result.data)
      productList.value = result.data
    } else {
      uni.showToast({
        title: '获取商品数据失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取商品数据失败:', error)
    uni.showToast({
      title: '获取商品数据失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

onLoad((options) => {
  if (options && options.supplierName) {
    supplierName.value = decodeURIComponent(options.supplierName)
    supplierRowid.value = decodeURIComponent(options.supplierRowid)
    console.log('接收到的供应商名称:', supplierName.value)
    console.log('接收到的供应商Rowid:', supplierRowid.value)
  }
  // 页面加载时可以从服务器获取商品数据
  getProductData()
})



</script>

<style lang="scss" scoped>
.add-product-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  
  .search-bar {
    background-color: #ffffff;
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    .search-input-wrapper {
      display: flex;
      align-items: center;
      background-color: #f8f8f8;
      border-radius: 32rpx;
      padding: 20rpx 30rpx;
      
      .search-input {
        flex: 1;
        margin-left: 20rpx;
        font-size: 28rpx;
        color: #333333;
        
        &::placeholder {
          color: #999999;
        }
      }
      
      .clear-btn {
        margin-left: 20rpx;
        padding: 10rpx;
      }
    }
  }
  
  .product-scroll {
    flex: 1;
    
    .loading-state {
      padding: 100rpx 0;
      text-align: center;
      
      .loading-text {
        color: #999999;
        font-size: 28rpx;
      }
    }
    
    .product-list {
      padding: 20rpx 30rpx 180rpx;
      
      .product-card {
        background-color: #ffffff;
        border-radius: 16rpx;
        padding: 30rpx;
        margin-bottom: 20rpx;
        display: flex;
        align-items: center;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
        
        .checkbox-wrapper {
          margin-right: 30rpx;
          
          .checkbox {
            width: 40rpx;
            height: 40rpx;
            border: 2rpx solid #ddd;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            
            &.checkbox-checked {
              background-color: #87CEEB;
              border-color: #87CEEB;
            }
          }
        }
        
        .product-image {
          width: 120rpx;
          height: 120rpx;
          margin-right: 30rpx;
          flex-shrink: 0;
          
          .image {
            width: 100%;
            height: 100%;
            border-radius: 12rpx;
            object-fit: cover;
          }
        }
        
        .product-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          overflow: hidden;
          
          .product-name {
            font-size: 32rpx;
            font-weight: bold;
            color: #333333;
            margin-bottom: 12rpx;
            line-height: 1.4;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }
          
          .product-code {
            font-size: 24rpx;
            color: #666666;
            margin-bottom: 8rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          
          .product-spec {
            font-size: 24rpx;
            color: #666666;
            margin-bottom: 8rpx;
          }
          
          .unavailable-stock {
            font-size: 24rpx;
            color: #ff4757;
            margin-bottom: 8rpx;
          }
          
          .available-stock {
            font-size: 24rpx;
            color: #2ed573;
          }
        }
      }
      
      .empty-state {
        padding: 100rpx 0;
        text-align: center;
        
        .empty-text {
          color: #999999;
          font-size: 28rpx;
        }
      }
    }
  }
  
  .bottom-actions {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #ffffff;
    padding: 30rpx;
    border-top: 1rpx solid #f0f0f0;
    z-index: 100;
    
    .confirm-btn {
      width: 100%;
      background: linear-gradient(to right, #48eceb, #0fcee9);
      color: #ffffff;
      border: none;
      border-radius: 32rpx;
      font-size: 32rpx;
      font-weight: bold;
      height: 88rpx;
      
      &.confirm-btn-disabled {
        background: #cccccc !important;
        color: #999999 !important;
        cursor: not-allowed;
        opacity: 0.6;
      }
    }
  }
}
</style>